package org.rxc.gift.exception;


import org.rxc.gift.util.AjaxResult;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

/**
 * 全局异常处理
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(BusinessException.class)
    public AjaxResult businessExceptionHandler(BusinessException e){
        e.printStackTrace();
        return AjaxResult.me().setSuccess(false).setMessage(e.getMessage()).setResultObj(e.getCode());
    }

    /**
     * 对jsr303校验的错误信息做处理
     * @param e
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public AjaxResult methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e){
        e.printStackTrace();
        BindingResult bindingResult = e.getBindingResult();
        List<ObjectError> allErrors = bindingResult.getAllErrors();
        StringBuffer stringBuffer = new StringBuffer();
        for (ObjectError allError : allErrors) {
            stringBuffer.append(allError.getDefaultMessage()+"!");
        }
        return AjaxResult.me().setSuccess(false).setMessage(stringBuffer.toString())
                .setResultObj(ResponseCode.RESPONSE_CODE_400.getCode())
                .setMessage(ResponseCode.RESPONSE_CODE_400.getMessage());
    }


    @ExceptionHandler(Exception.class)
    public AjaxResult exceptionHandler(Exception e){
        e.printStackTrace();
        return AjaxResult.me().setSuccess(false).setMessage("网络异常,请刷新重试!")
                .setResultObj(ResponseCode.RESPONSE_CODE_500.getCode())
                .setMessage(ResponseCode.RESPONSE_CODE_500.getMessage());
    }

}
